package cn.bluech.template;

import android.text.TextUtils;

import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.EncryptionMethod;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import cn.bluech.lib.utils.ListUtils;

/**
 * Description:
 */
public class Zip {
    private ZipFile zipFile;
    // 压缩
    private ZipParameters param;

    public static Zip create(File outFile, String pwd){
        Zip zip = new Zip(pwd);
        outFile.delete();
        zip.zipFile = new ZipFile(outFile,pwd.toCharArray());

        return zip;
    }

    public static Zip open(File zipFile, String pwd){
        Zip zip = new Zip(pwd);
        zip.zipFile = new ZipFile(zipFile,pwd.toCharArray());

        return zip;
    }


    private Zip(String pwd) {
        param = new ZipParameters();
        if (!TextUtils.isEmpty(pwd)) {
            param.setEncryptFiles(true);
            param.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); // 加密方式
        }
    }

    public boolean isValid(){
        return zipFile.isValidZipFile();
    }

    public Zip addFile(String destDir, File input) throws ZipException {
        param.setRootFolderNameInZip(destDir);
        zipFile.addFile(input,param);

        return this;
    }

    public List<String> getFiles(){
        List<FileHeader> headers = getHeaders();

        if(ListUtils.isEmpty(headers))
            return new ArrayList<>();

        List<String> files = new ArrayList<>(headers.size());
        for(FileHeader header:headers){
            files.add(header.getFileName());
        }
        return files;
    }

    public List<FileHeader> getHeaders(){
        try {
            return zipFile.getFileHeaders();
        } catch (ZipException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    public InputStream getFile(String fileName){
        List<FileHeader> headers = getHeaders();
        if(ListUtils.isEmpty(headers))
            return null;

        try {
            for (FileHeader header : headers) {
                if (header.getFileName().equals(fileName))
                    return zipFile.getInputStream(header);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public InputStream getFile(FileHeader header){
        try {
            return zipFile.getInputStream(header);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}




